<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\services\system;

use common\models\system\AdminRole;
use common\models\system\Role;
use common\models\system\RoleDept;
use common\models\system\RoleMenu;
use common\services\PermissionService;
use Yii;
use yii\db\Exception;

class RoleService
{
    /**
     * 判断用户是否包含有个角色
     * @param $userId
     * @param $roleId
     * @return bool
     */
    public static function checkUserIsRole($userId, $roleId): bool
    {
        if (!$userId || !$roleId) return false;
        $info = AdminRole::findOne(['admin_id' => $userId, 'role_id' => $roleId]);
        return $info ? true : false;
    }

    /**
     * 获取某个用户的角色列表
     * @param int|string $userId
     * @return array
     */
    public static function selectRoleByUserId($userId): array
    {
        if (!$userId) return [];
        $list = Role::find()->alias('r')->select(['r.id', 'r.name', 'r.role_key', 'r.data_scope', 'r.status', 'r.list_sort'])
            ->leftJoin(AdminRole::tableName() . ' ar', 'ar.role_id = r.id')
            ->where(['ar.admin_id' => $userId])
            ->orderBy('r.list_sort asc, r.id asc')->distinct()->asArray()->all();
        return $list ?: [];
    }

    /**
     * 某个用户可选择列表
     * @param $userId
     * @return array
     */
    public static function selectRoleUserSelectList($userId): array
    {
        if (PermissionService::isAdmin($userId)) return self::getList();
        return self::selectRoleByUserId($userId);
    }

    /**
     * 获取列表
     * @param bool $all
     * @return array
     */
    public static function getList($all = true): array
    {
        $list = Role::find()->select(['id', 'name', 'role_key', 'status', 'data_scope']);
        if (!$all) $list = $list->where(['status' => 1]);
        $list = $list->orderBy('list_sort asc, id asc')->asArray()->all();
        return $list ?: [];
    }


    /**
     * 获取角色分组的菜单权限ID
     * @param string|array|int $roleId
     * @return array
     */
    public static function selectRoleMenuListByRole($roleId): array
    {
        if (!$roleId) return [];
        $list = RoleMenu::find()->select(['menu_id'])->where(['role_id' => $roleId])->column();
        return $list ? array_unique($list) : [];
    }


    /**
     * 获取角色的自定义数据权限部门ID
     * @param string|array|int $roleId
     * @return array
     */
    public static function selectRoleDeptListByRole($roleId): array
    {
        if (!$roleId) return [];
        $list = RoleDept::find()->where(['role_id' => $roleId])->asArray()->all();
        return $list ? array_unique(array_column($list, 'dept_id')) : [];
    }

    /**
     * 更新 角色权限菜单
     * @param $roleId
     * @param string|array|int $menuIds
     * @return bool
     */
    public static function updateRoleMenuIds($roleId, $menuIds): bool
    {
        if (!$roleId) return false;
        RoleMenu::deleteAll(['role_id' => $roleId]);

        $menuIds = $menuIds ? array_unique(is_array($menuIds) ? $menuIds : explode(',', $menuIds)) : [];

        $data = [];
        foreach ($menuIds as $menuId) {
            if ($menuId) $data[] = [$roleId, $menuId];
        }
        if (!$data) return true;
        try {
            Yii::$app->db->createCommand()->batchInsert(RoleMenu::tableName(), ['role_id', 'menu_id'], $data)->execute();
            return true;
        } catch (Exception $exception) {
            return false;
        }
    }

    /**
     * 更新 角色数据权限自定义组织
     * @param $roleId
     * @param string|array|int $deptIds
     * @return bool
     */
    public static function updateRoleDeptIds($roleId, $deptIds): bool
    {
        if (!$roleId) return false;
        RoleDept::deleteAll(['role_id' => $roleId]);

        $deptIds = $deptIds ? array_unique(is_array($deptIds) ? $deptIds : explode(',', $deptIds)) : [];

        $data = [];
        foreach ($deptIds as $deptId) {
            if ($deptId) $data[] = [$roleId, $deptId];
        }
        if (!$data) return true;
        try {
            Yii::$app->db->createCommand()->batchInsert(RoleDept::tableName(), ['role_id', 'dept_id'], $data)->execute();
            return true;
        } catch (Exception $exception) {
            return false;
        }
    }

    /**
     * 检测某个用户是否有某个角色
     * @param string|integer $userId
     * @param string|integer $roleId
     * @return bool
     */
    public static function checkHasRolePerm($userId, $roleId): bool
    {
        if (PermissionService::isAdmin($userId)) return true;
        if (!$userId || !$roleId) return false;
        $roleList = self::selectRoleUserSelectList($userId);
        foreach ($roleList as $role) {
            if ($role['id'] == $roleId && $role['status'] == '1') return true;
        }
        return false;
    }

}
